from flask import Blueprint, request, flash, redirect, url_for, render_template
from flask_login import login_required
from datetime import datetime
from inc.models import db, JiraProject, JiraReview
from ..utils import member_login_required, get_current_member
from ..workflow.services import ProjectWorkflow
import logging

# 配置日志
logger = logging.getLogger(__name__)

closure_bp = Blueprint('closure', __name__, url_prefix='/closure')

@closure_bp.route('/request/<int:project_id>', methods=['POST'])
@member_login_required
def request_closure(project_id):
    """提交结项申请"""
    current_member = get_current_member()
    try:
        ProjectWorkflow.request_project_closure(project_id, current_member.id)
        flash('结项申请已提交', 'success')
    except Exception as e:
        flash(str(e), 'danger')
    return redirect(url_for('member.jira.project_detail', project_id=project_id))

@closure_bp.route('/approve/<int:project_id>', methods=['POST'])
@member_login_required
def approve_closure(project_id):
    """批准结项"""
    current_member = get_current_member()
    notes = request.form.get('notes', '')
    try:
        ProjectWorkflow.approve_project_closure(
            project_id,
            current_member.id,
            notes
        )
        flash('结项已批准', 'success')
    except Exception as e:
        flash(str(e), 'danger')
    return redirect(url_for('member.jira.project_detail', project_id=project_id))

@closure_bp.route('/<int:approval_id>/detail')
@member_login_required
def closure_detail(approval_id):
    """结项审批详情页"""
    try:
        approval = JiraReview.query.options(
            db.joinedload(JiraReview.project),
            db.joinedload(JiraReview.submitter),
            db.joinedload(JiraReview.reviewer)
        ).get_or_404(approval_id)

        # 获取审批历史
        history = JiraReview.query.filter_by(
            project_id=approval.project_id,
            is_closure_review=True
        ).order_by(JiraReview.created_at.desc()).all()

        return render_template(
            'member/closure/closure_detail.html',
            approval=approval,
            project=approval.project,
            history=history
        )
    except Exception as e:
        logger.error(f"加载结项审批详情失败: {str(e)}", exc_info=True)
        flash('加载结项审批详情失败', 'danger')
        return redirect(url_for('member.dashboard'))

@closure_bp.route('/review/<int:approval_id>', methods=['POST'])
@member_login_required
def review(approval_id):
    """处理结项审批"""
    current_member = get_current_member()
    action = request.form.get('action')
    notes = request.form.get('notes', '')

    try:
        approval = JiraReview.query.get_or_404(approval_id)

        if action == 'approve':
            ProjectWorkflow.approve_project_closure(
                approval.project_id,
                current_member.id,
                notes
            )
            flash('结项已批准', 'success')
        elif action == 'reject':
            ProjectWorkflow.reject_project_closure(
                approval.project_id,
                current_member.id,
                notes
            )
            flash('结项已拒绝', 'success')
        else:
            flash('无效的操作', 'danger')

        return redirect(url_for('member.closure.closure_detail', approval_id=approval_id))
    except Exception as e:
        logger.error(f"处理结项审批失败: {str(e)}", exc_info=True)
        flash(str(e), 'danger')
        return redirect(url_for('member.closure.closure_detail', approval_id=approval_id))

@closure_bp.route('/reject/<int:project_id>', methods=['POST'])
@member_login_required
def reject_closure(project_id):
    """拒绝结项"""
    current_member = get_current_member()
    notes = request.form.get('notes', '')
    try:
        ProjectWorkflow.reject_project_closure(
            project_id,
            current_member.id,
            notes
        )
        flash('结项已拒绝', 'success')
    except Exception as e:
        logger.error(f"拒绝结项失败: {str(e)}", exc_info=True)
        flash(str(e), 'danger')
    return redirect(url_for('member.jira.project_detail', project_id=project_id))